package com.jd.risk.bankorder.util.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class FileUtil {

	private static String message;

	public FileUtil() {
	}

	public static void main(String[] args) throws Exception {
		// moveFolder("f:/aaa","f:/bbb");
		File f = new File("e:/TTPod_Android_v2.8.apk");
		System.out.println(f.length());
		System.out.println(formatFileSize(f.length()));
	}

	/**
	 * 格式化文件大小，通过对输入的文件的长度，来转换为适当的单位表示（GB、MB、KB）
	 * 
	 * @param long length
	 * @return String result
	 * */
	public static String formatFileSize(long length) {
		String result = null;
		int sub_string = 0;
		if (length >= 1073741824) {
			sub_string = String.valueOf((float) length / 1073741824).indexOf(".");
			result = ((float) length / 1073741824 + "000").substring(0,// 1073741824
					sub_string + 3) + "GB";
		} else if (length >= 1048576) {
			sub_string = String.valueOf((float) length / 1048576).indexOf(".");
			result = ((float) length / 1048576 + "000").substring(0,// 1048576
					sub_string + 3) + "MB";
		} else if (length >= 1024) {
			sub_string = String.valueOf((float) length / 1024).indexOf(".");
			result = ((float) length / 1024 + "000").substring(0,// 1024
					sub_string + 3) + "KB";
		} else if (length < 1024)
			result = Long.toString(length) + "B";
		return result;
	}

	public static byte[] readFile(String file, int bufLen) throws Exception {
		InputStream in = null;
		byte[] buf = null; // output buffer
		// int bufLen = 20000*1024; //ÿ��20M
		int totalLen = 0;

		try {
			in = new BufferedInputStream(new FileInputStream(file));

			buf = new byte[bufLen];
			byte[] tmp = null;
			int len = 0;
			List<byte[]> data = new ArrayList<byte[]>();

			while ((len = in.read(buf, 0, bufLen)) != -1) {
				tmp = new byte[len];
				System.arraycopy(buf, 0, tmp, 0, len);
				data.add(tmp);
				totalLen = totalLen + len;
			}

			// len = 0;
			if (data.size() == 1)
				return data.get(0);
			// for (int i=0;i<data.size();i++) len += data.get(i).length;
			buf = new byte[totalLen];
			len = 0;
			for (int i = 0; i < data.size(); i++) {
				tmp = data.get(i);
				System.arraycopy(tmp, 0, buf, len, tmp.length);
				len += tmp.length;
			}
		} catch (Exception e) {
			// log.error(">>>>>>>>>" + StringUtil.getCurrentDateTime() + " read
			// file " + file + " error!");
			e.printStackTrace();
		} finally {
			if (in != null)
				try {
					in.close();
				} catch (Exception e) {
				}
		}

		return buf;
	}

	public static boolean writeFileFromBytes(String toFile, byte[] data) {
		boolean ret = false;
		PrintStream out = null;
		try {
			out = new PrintStream(new BufferedOutputStream(new FileOutputStream(toFile)));
			out.write(data);
			ret = true;
		} catch (Exception e) {
			try {
				out.close();
			} catch (Exception e2) {
			}
			ret = false;
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (Exception ex) {
			}
		}
		return ret;
	}

	public static boolean renameFile(String filePath, String newName) {
		boolean b = false;

		try {
			File f = new File(filePath);
			File fn = new File(newName);
			if (f.exists()) {
				return f.renameTo(fn);
			}
		} catch (Exception e) {
		} finally {

		}
		return b;

	}

	public static byte[] readFileToByteArrays(String filePathAndName) throws IOException {

		InputStream input = null;
		byte b[] = null;
		try {
			File f = new File(filePathAndName);
			if (f.exists()) {
				// 准备好一个输入的对象
				input = new FileInputStream(f);
				// 通过对象多态性进行实例化
				// 第3步：进行读操作
				b = new byte[(int) f.length()];
				// 所有的内容读到此数组中，数组 大小由文件决定
				input.read(b); // 将内容读出
				// 第4步：关闭输入流
				input.close();

				// 关闭输入流
				// System.out.println("内容为：" + b.length); // 把byte数组变为字符 串输出
			}
		} catch (Exception e) {
		} finally {
			try {
				if (input != null) {
					input.close();
				}
			} catch (Exception ex) {
			}
		}

		return b;
	}

	public static String readTxt(String filePathAndName, String encoding) {
		encoding = encoding.trim();
		StringBuffer str = new StringBuffer("");
		String st = "";
		FileInputStream fs = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		try {
			fs = new FileInputStream(filePathAndName);
			if (encoding.equals("")) {
				isr = new InputStreamReader(fs);
			} else {
				isr = new InputStreamReader(fs, encoding);
			}
			br = new BufferedReader(isr);
			try {
				String data = "";
				while ((data = br.readLine()) != null) {
					str.append(data);
				}
			} catch (Exception e) {
				str.append(e.toString());
			}
			st = str.toString();
		} catch (IOException es) {
			st = "-1";
		} finally {
			try {
				if (fs != null) {
					fs.close();
				}
				if (isr != null) {
					isr.close();
				}
				if (br != null) {
					br.close();
				}
			} catch (Exception ex) {
			}
		}
		return st;
	}

	public static String createFile(String folderPath) {
		// System.out.println(folderPath);
		String txt = folderPath;
		try {
			java.io.File myFile = new java.io.File(txt);
			txt = folderPath;
			if (!myFile.exists()) {
				myFile.createNewFile();
				txt = "";
			} else {
				txt = "";
			}
		} catch (Exception e) {
			txt = "";
			message = "";
		}
		return txt;
	}

	public static boolean isFile(String folderPath) {
		boolean b = false;
		String txt = folderPath;
		try {
			java.io.File myFile = new java.io.File(txt);
			txt = folderPath;
			if (myFile.exists()) {
				b = true;
			}
		} catch (Exception e) {
		}
		return b;
	}

	public static boolean isFolder(String folderPath) {
		boolean b = false;
		try {
			java.io.File myFilePath = new java.io.File(folderPath);
			if (myFilePath.isDirectory()) {
				b = true;
			}
		} catch (Exception e) {
		}
		return b;
	}

	public static String createFolder(String folderPath) {
		String txt = folderPath;
		try {
			java.io.File myFilePath = new java.io.File(txt);
			txt = folderPath;
			if (!myFilePath.isDirectory()) {
				myFilePath.mkdir();
			}
		} catch (Exception e) {
			message = "-1";
		}
		return txt;
	}

	public static String createFolders(String folderPath, String paths) {
		String txts = folderPath;
		String root = "";
		try {
			String txt;
			txts = folderPath;
			StringTokenizer st = new StringTokenizer(paths, "|");
			for (int i = 0; st.hasMoreTokens(); i++) {
				txt = st.nextToken().trim();
				if (root.lastIndexOf("/") != -1) {
					txts = createFolder(root + txt);
				} else {
					root = createFolder(txts + txt + "/");
				}
				txt = "";
			}
		} catch (Exception e) {
			// txts = Constants.SERVER_ERROR;
			message = "";
		}
		return txts;
	}

	public static String createFile(String filePathAndName, String fileContent) {

		String str = "";
		try {
			String filePath = filePathAndName;
			filePath = filePath.toString();
			File myFilePath = new File(filePath);
			if (!myFilePath.exists()) {
				myFilePath.createNewFile();
			}
			FileWriter resultFile = new FileWriter(myFilePath);
			PrintWriter myFile = new PrintWriter(resultFile);
			String strContent = fileContent;
			myFile.println(strContent);
			myFile.close();
			resultFile.close();
		} catch (Exception e) {
			str = "-1";
			message = "";
		}

		return str;
	}

	public static void createFile(String filePathAndName, String fileContent, String encoding) {

		try {
			String filePath = filePathAndName;
			filePath = filePath.toString();
			File myFilePath = new File(filePath);
			if (!myFilePath.exists()) {
				myFilePath.createNewFile();
			}
			PrintWriter myFile = new PrintWriter(myFilePath, encoding);
			String strContent = fileContent;
			myFile.println(strContent);
			myFile.close();
		} catch (Exception e) {
			message = "";
		}
	}

	public static boolean delFile(String filePathAndName) {
		boolean bea = false;
		try {
			String filePath = filePathAndName;
			File myDelFile = new File(filePath);
			if (myDelFile.isAbsolute()) {
				// System.gc();
				bea = myDelFile.delete();
			} else {
				bea = false;
				message = (filePathAndName + "");
			}
		} catch (Exception e) {
			message = e.toString();
		}
		return bea;
	}

	public static boolean delFolder(String folderPath) {
		boolean b = false;
		try {
			delAllFile(folderPath); //
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			b = myFilePath.delete(); //
		} catch (Exception e) {
			message = ("");
		}
		return b;
	}

	public static boolean delFolders(String folderPath) {
		boolean b = false;
		String txt = folderPath;
		try {
			java.io.File myFilePath = new java.io.File(txt);
			txt = folderPath;
			if (myFilePath.exists()) {
				System.gc();
				b = myFilePath.delete();
			}
			// b = true;
		} catch (Exception e) {
			txt = "";
			message = "";
		}
		return b;
	}

	/*
	 * public static void delZips(String path) { File dir = new File(path); if
	 * (dir.isDirectory()) { File[] fs = dir.listFiles(); for (int k = 0; k <
	 * fs.length; k++) { dir = fs[k]; if
	 * (dir.getName().indexOf(Constants.EXTENSION_NAME_ZIP) > -1) {
	 * dir.delete(); } } } }
	 */

	public static boolean delAllFile(String path) {
		boolean bea = false;
		File file = new File(path);
		if (!file.exists()) {
			return bea;
		}
		if (!file.isDirectory()) {
			return bea;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);//
				delFolder(path + "/" + tempList[i]);//
				bea = true;
			}
		}
		return bea;
	}

	public static void copyFile(String oldPathFile, String newPathFile) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPathFile);
			if (oldfile.exists()) { //
				InputStream inStream = new FileInputStream(oldPathFile); //
				FileOutputStream fs = new FileOutputStream(newPathFile);
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; //
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
			}
		} catch (Exception e) {
			message = ("");
		}
	}

	public static void copyFolder(String oldPath, String newPath) {
		try {
			new File(newPath).mkdirs(); //
			File a = new File(oldPath);
			String[] file = a.list();
			File temp = null;
			for (int i = 0; i < file.length; i++) {
				if (oldPath.endsWith(File.separator)) {
					temp = new File(oldPath + file[i]);
				} else {
					temp = new File(oldPath + File.separator + file[i]);
				}
				if (temp.isFile()) {
					FileInputStream input = new FileInputStream(temp);
					FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()).toString());
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = input.read(b)) != -1) {
						output.write(b, 0, len);
					}
					output.flush();
					output.close();
					input.close();
				}
				if (temp.isDirectory()) {//
					copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
				}
			}
		} catch (Exception e) {
			message = "";
		}
	}

	public static void moveFile(String oldPath, String newPath) {
		copyFile(oldPath, newPath);
		delFile(oldPath);
	}

	public static void moveFolder(String newPath, String oldPath) {
		// 拷贝新文件夹文件到旧文件夹
		copyFolder(newPath, oldPath);
		// 删除旧文件夹
		delFolder(newPath);
	}

}